package com.lenovo.agricultureServer.http.action;

import org.json.JSONException;
import org.json.JSONObject;

import com.lenovo.agricultureServer.bean.Controller;

import android.R.integer;
import android.content.Context;
import android.content.Intent;

public class ControlAction extends BaseAction 
{
	public static final String TAG = "control";
	
	private Context context;
	public ControlAction(Context context)
	{
		this.context = context;
	}
	
	@Override
	protected String jasonPorcess(String param) 
	{
		JSONObject jsonResponse = new JSONObject();
		try 
		{
			JSONObject jsonRequest = new JSONObject(param);
			// 处理控制器请求
			String controlDevices[] = {Controller.WATER_PUMP_CONTORL, Controller.BLOWER_CONTORL, Controller.ROADLAMP_CONTORL, Controller.BUZZER_CONTORL};
			for(String device : controlDevices)
			{
				if(jsonRequest.has(device)){
					controlDevice(device,jsonRequest.getInt(device));
				}
			}
			jsonResponse.put("result", "ok");
			return jsonResponse.toString();
		} 
		catch (JSONException e) 
		{
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected String soapPorcess(String param) {
		//TODO
		return "";
	}
	
	//向串口service发送广播,控制外设的开启与关闭
	private void controlDevice(String device, int isOpen)
	{
		Intent intent = new Intent("com.lenovo.agriculture.server.broadcat.senttoserialport");
		intent.putExtra("message", "control");
		intent.putExtra("device", device);
		intent.putExtra("isOpen", isOpen);
		context.sendBroadcast(intent);
	}

}
